﻿using CSRedis;

namespace PMS.WebApi.Extensions
{
    public static class RedisDistributedLockExtension
    {
        #region 推荐使用
        /// <summary>
        /// 加锁毫秒级
        /// </summary>
        /// <param name="client">redis客户端连接</param>
        /// <param name="key">锁key</param>
        /// <param name="value">锁值</param>
        /// <param name="expireMillSeconds">缓存时间（单位/毫秒，默认1000毫秒）</param>
        /// <returns></returns>
        public static bool RedisLock(this CSRedisClient client, string key, object value, int expireMillSeconds = 1000)
        {
            var script = @"local isNX = redis.call('SETNX',KEYS[1],ARGV[1])
                           if isNX == 1 then
                                redis.call('PEXPIRE',KEYS[1],ARGV[2])
                                return 1
                           end
                           return 0";
            return client.Eval(script, key, value, expireMillSeconds)?.ToString() == "1";
        }
        /// <summary>
        /// 解锁
        /// </summary>
        /// <param name="client">redis客户端连接</param>
        /// <param name="key">锁key</param>
        /// <param name="value">锁值</param>
        /// <param name="selfMark">对应加锁客户端标识</param>
        /// <returns></returns>
        public static bool RedisUnLock(this CSRedisClient client, string key, string selfMark)
        {
            var script = @"local getLock = redis.call('GET',KEYS[1])
                           if getLock == ARGV[1] then
                                redis.call('DEL',KEYS[1])
                                return 1
                           end
                           return 0";
            return client.Eval(script, key, selfMark)?.ToString() == "1";
        }
        #endregion
    }
}
